import React, { memo, useEffect, useState, useMemo } from 'react';
import { 
  Card, 
  Button, 
  Row, 
  Col, 
  Space, 
  Typography, 
  Divider,
  Modal,
  message,
  Spin,
  Tabs,
  Badge,
  Select,
  Tag
} from 'antd';
import { 
  PlusOutlined, 
  BookOutlined, 
  TagsOutlined,
  EditOutlined,
  DeleteOutlined,
  ExclamationCircleOutlined,
  FilterOutlined,
  ClearOutlined
} from '@ant-design/icons';
import { useSearchParams } from 'react-router-dom';
import { 
  CourseCard, 
  CourseForm, 
  CourseList, 
  CourseSearch,
  CourseCategoryCard,
  CourseCategoryForm,
  CourseCategorySelector
} from '@/components/business/course';
import { 
  useCourseManagement, 
  useCategoryManagement,
  useCourseFilter,
  useCourseSelection
} from '@/store/course';
import type { ICourse, ICourseCategory } from '@/types/course';
import styles from './CoursePage.module.css';

const { Title, Text } = Typography;
const { TabPane } = Tabs;
const { Option } = Select;
const { confirm } = Modal;

/**
 * 课程管理页面组件
 * @description 提供课程和分类的增删改查功能，支持分类筛选
 */
const CoursePage: React.FC = memo(() => {
  const [searchParams, setSearchParams] = useSearchParams();
  
  // 本地状态
  const [showCourseForm, setShowCourseForm] = useState(false);
  const [showCategoryForm, setShowCategoryForm] = useState(false);
  const [courseFormMode, setCourseFormMode] = useState<'create' | 'edit'>('create');
  const [categoryFormMode, setCategoryFormMode] = useState<'create' | 'edit'>('create');
  const [currentCourse, setCurrentCourse] = useState<ICourse | null>(null);
  const [currentCategory, setCurrentCategory] = useState<ICourseCategory | null>(null);
  const [activeTab, setActiveTab] = useState('courses');

  // 状态管理
  const {
    courses,
    fetchCourses,
    addCourse,
    updateCourse,
    deleteCourse
  } = useCourseManagement();

  const {
    categories,
    fetchCategories,
    addCategory,
    updateCategory,
    deleteCategory
  } = useCategoryManagement();

  const {
    filters,
    filteredCourses,
    updateFilters,
    setSearchKeyword
  } = useCourseFilter();

  const {
    selectedCourseIds,
    selectedCourses,
    toggleSelection,
    clearSelection
  } = useCourseSelection();

  // 初始化数据
  useEffect(() => {
    const initializeData = async () => {
      try {
        await Promise.all([
          fetchCourses(),
          fetchCategories()
        ]);
      } catch (error) {
        console.error('初始化课程页面数据失败:', error);
        message.error('加载数据失败，请刷新页面重试');
      }
    };

    initializeData();
  }, []); // 移除函数依赖，避免无限循环

  // 处理URL参数
  useEffect(() => {
    const action = searchParams.get('action');
    const courseId = searchParams.get('courseId');
    const categoryId = searchParams.get('categoryId');

    if (action === 'create') {
      handleCreateCourse();
    } else if (action === 'edit' && courseId) {
      const course = courses.find(c => c.id === courseId);
      if (course) {
        handleEditCourse(course);
      }
    } else if (action === 'create-category') {
      handleCreateCategory();
    } else if (action === 'edit-category' && categoryId) {
      const category = categories.find(c => c.id === categoryId);
      if (category) {
        handleEditCategory(category);
      }
    }
  }, [searchParams, courses, categories]);

  // 课程统计
  const courseStats = useMemo(() => {
    const stats = {
      total: courses.length,
      active: courses.filter(c => c.status === 1).length,
      suspended: courses.filter(c => c.status === 2).length,
      byCategory: {} as Record<string, number>
    };

    // 按分类统计
    categories.forEach(category => {
      stats.byCategory[category.id] = courses.filter(course => 
        course.categoryIds.includes(category.id)
      ).length;
    });

    return stats;
  }, [courses, categories]);

  // 分类统计
  const categoryStats = useMemo(() => {
    return {
      total: categories.length,
      active: categories.filter(c => c.status === 1).length,
      disabled: categories.filter(c => c.status === 2).length
    };
  }, [categories]);

  // 获取课程的分类信息
  const getCourseCategories = (course: ICourse): ICourseCategory[] => {
    return categories.filter(category => course.categoryIds.includes(category.id));
  };

  // 创建课程
  const handleCreateCourse = () => {
    setCurrentCourse(null);
    setCourseFormMode('create');
    setShowCourseForm(true);
    setSearchParams({});
  };

  // 编辑课程
  const handleEditCourse = (course: ICourse) => {
    setCurrentCourse(course);
    setCourseFormMode('edit');
    setShowCourseForm(true);
  };

  // 删除课程
  const handleDeleteCourse = (course: ICourse) => {
    confirm({
      title: '确认删除课程',
      icon: <ExclamationCircleOutlined />,
      content: (
        <div>
          <p>确定要删除课程 <strong>{course.name}</strong> 吗？</p>
          <p style={{ color: '#ff4d4f', fontSize: '12px' }}>
            删除后该课程的所有课程安排也将被删除，此操作不可恢复。
          </p>
        </div>
      ),
      okText: '确认删除',
      okType: 'danger',
      cancelText: '取消',
      onOk: async () => {
        try {
          await deleteCourse(course.id);
          message.success('课程删除成功');
          clearSelection();
        } catch (error) {
          console.error('删除课程失败:', error);
          message.error('删除课程失败，请重试');
        }
      }
    });
  };

  // 创建分类
  const handleCreateCategory = () => {
    setCurrentCategory(null);
    setCategoryFormMode('create');
    setShowCategoryForm(true);
    setSearchParams({});
  };

  // 编辑分类
  const handleEditCategory = (category: ICourseCategory) => {
    setCurrentCategory(category);
    setCategoryFormMode('edit');
    setShowCategoryForm(true);
  };

  // 删除分类
  const handleDeleteCategory = (category: ICourseCategory) => {
    const relatedCourses = courses.filter(course => 
      course.categoryIds.includes(category.id)
    );

    if (relatedCourses.length > 0) {
      Modal.warning({
        title: '无法删除分类',
        content: (
          <div>
            <p>该分类下还有 <strong>{relatedCourses.length}</strong> 个课程，无法删除。</p>
            <p>请先将这些课程移动到其他分类或删除这些课程。</p>
          </div>
        )
      });
      return;
    }

    confirm({
      title: '确认删除分类',
      icon: <ExclamationCircleOutlined />,
      content: `确定要删除分类 "${category.name}" 吗？此操作不可恢复。`,
      okText: '确认删除',
      okType: 'danger',
      cancelText: '取消',
      onOk: async () => {
        try {
          await deleteCategory(category.id);
          message.success('分类删除成功');
        } catch (error) {
          console.error('删除分类失败:', error);
          message.error('删除分类失败，请重试');
        }
      }
    });
  };

  // 课程表单提交
  const handleCourseFormSubmit = async (formData: any) => {
    try {
      if (courseFormMode === 'create') {
        await addCourse(formData);
        message.success('课程添加成功');
      } else {
        await updateCourse(currentCourse!.id, formData);
        message.success('课程信息更新成功');
      }
      setShowCourseForm(false);
      setCurrentCourse(null);
    } catch (error) {
      console.error('保存课程信息失败:', error);
      message.error(courseFormMode === 'create' ? '添加课程失败' : '更新课程信息失败');
    }
  };

  // 分类表单提交
  const handleCategoryFormSubmit = async (formData: any) => {
    try {
      if (categoryFormMode === 'create') {
        await addCategory(formData);
        message.success('分类添加成功');
      } else {
        await updateCategory(currentCategory!.id, formData);
        message.success('分类信息更新成功');
      }
      setShowCategoryForm(false);
      setCurrentCategory(null);
    } catch (error) {
      console.error('保存分类信息失败:', error);
      message.error(categoryFormMode === 'create' ? '添加分类失败' : '更新分类信息失败');
    }
  };

  // 批量删除课程
  const handleBatchDeleteCourses = () => {
    if (selectedCourseIds.length === 0) {
      message.warning('请先选择要删除的课程');
      return;
    }

    confirm({
      title: '批量删除课程',
      icon: <ExclamationCircleOutlined />,
      content: `确定要删除选中的 ${selectedCourseIds.length} 个课程吗？此操作不可恢复。`,
      okText: '确认删除',
      okType: 'danger',
      cancelText: '取消',
      onOk: async () => {
        try {
          await Promise.all(selectedCourseIds.map(id => deleteCourse(id)));
          message.success(`成功删除 ${selectedCourseIds.length} 个课程`);
          clearSelection();
        } catch (error) {
          console.error('批量删除课程失败:', error);
          message.error('批量删除失败，请重试');
        }
      }
    });
  };

  const isLoading = false; // TODO: 从 store 中获取加载状态

  return (
    <div className={styles.coursePage}>
      {/* 页面头部 */}
      <div className={styles.pageHeader}>
        <div className={styles.headerContent}>
          <div className={styles.titleSection}>
            <Title level={2} className={styles.pageTitle}>
              <BookOutlined /> 课程管理
            </Title>
            <Text type="secondary">
              管理课程信息和分类，支持分类筛选和搜索
            </Text>
          </div>
          <div className={styles.actionSection}>
            <Space>
              {selectedCourseIds.length > 0 && (
                <>
                  <Button 
                    danger 
                    onClick={handleBatchDeleteCourses}
                    icon={<DeleteOutlined />}
                  >
                    批量删除 ({selectedCourseIds.length})
                  </Button>
                  <Button onClick={clearSelection}>
                    取消选择
                  </Button>
                </>
              )}
              <Button 
                type="primary" 
                icon={<PlusOutlined />}
                onClick={handleCreateCourse}
              >
                添加课程
              </Button>
            </Space>
          </div>
        </div>

        {/* 统计信息 */}
        <Row gutter={16} className={styles.statsRow}>
          <Col span={6}>
            <Card className={styles.statCard}>
              <div className={styles.statContent}>
                <div className={styles.statNumber}>{courseStats.total}</div>
                <div className={styles.statLabel}>总课程数</div>
              </div>
            </Card>
          </Col>
          <Col span={6}>
            <Card className={styles.statCard}>
              <div className={styles.statContent}>
                <div className={styles.statNumber} style={{ color: '#52c41a' }}>
                  {courseStats.active}
                </div>
                <div className={styles.statLabel}>正常课程</div>
              </div>
            </Card>
          </Col>
          <Col span={6}>
            <Card className={styles.statCard}>
              <div className={styles.statContent}>
                <div className={styles.statNumber} style={{ color: '#faad14' }}>
                  {courseStats.suspended}
                </div>
                <div className={styles.statLabel}>暂停课程</div>
              </div>
            </Card>
          </Col>
          <Col span={6}>
            <Card className={styles.statCard}>
              <div className={styles.statContent}>
                <div className={styles.statNumber} style={{ color: '#1890ff' }}>
                  {categoryStats.total}
                </div>
                <div className={styles.statLabel}>课程分类</div>
              </div>
            </Card>
          </Col>
        </Row>
      </div>

      <Divider />

      {/* 主要内容 */}
      <div className={styles.pageContent}>
        <Spin spinning={isLoading}>
          <Tabs 
            activeKey={activeTab} 
            onChange={setActiveTab}
            className={styles.contentTabs}
          >
            <TabPane 
              tab={
                <span>
                  <BookOutlined />
                  课程列表
                  <Badge count={filteredCourses.length} showZero style={{ marginLeft: 8 }} />
                </span>
              } 
              key="courses"
            >
              <Card className={styles.listCard}>
                {/* 搜索和筛选区域 */}
                <div className={styles.filterSection}>
                  <Row gutter={16} align="middle">
                    <Col flex="auto">
                      <CourseSearch
                        categories={categories}
                        onSearch={setSearchKeyword}
                        placeholder="搜索课程名称、教师、地点..."
                      />
                    </Col>
                    <Col>
                      <Space>
                        <Select
                          placeholder="选择分类"
                          style={{ width: 150 }}
                          allowClear
                          value={filters.filters.categoryId}
                          onChange={(value) => updateFilters({ categoryId: value })}
                        >
                          {categories.map(category => (
                            <Option key={category.id} value={category.id}>
                              <Tag color={category.color}>{category.name}</Tag>
                            </Option>
                          ))}
                        </Select>
                        <Select
                          placeholder="课程状态"
                          style={{ width: 120 }}
                          allowClear
                          value={filters.filters.status}
                          onChange={(value) => updateFilters({ status: value })}
                        >
                          <Option value={1}>正常</Option>
                          <Option value={2}>暂停</Option>
                        </Select>
                        <Button 
                          icon={<ClearOutlined />}
                          onClick={() => updateFilters({})}
                          disabled={!filters.filters.categoryId && !filters.filters.status && !filters.searchKeyword}
                        >
                          清除筛选
                        </Button>
                      </Space>
                    </Col>
                  </Row>
                </div>

                {/* 课程列表 */}
                <CourseList
                  courses={filteredCourses}
                  categories={categories}
                  loading={false}
                  selectedCourseIds={selectedCourseIds}
                  onSelect={(courseIds: string[]) => {
                    courseIds.forEach(id => toggleSelection(id));
                  }}
                  onEdit={handleEditCourse}
                  onDelete={(id) => {
                    const course = courses.find(c => c.id === id);
                    if (course) handleDeleteCourse(course);
                  }}
                  className={styles.courseList}
                />
              </Card>
            </TabPane>

            <TabPane 
              tab={
                <span>
                  <TagsOutlined />
                  分类管理
                  <Badge count={categories.length} showZero style={{ marginLeft: 8 }} />
                </span>
              } 
              key="categories"
            >
              <Card 
                className={styles.categoryCard}
                extra={
                  <Button 
                    type="primary" 
                    icon={<PlusOutlined />}
                    onClick={handleCreateCategory}
                  >
                    添加分类
                  </Button>
                }
              >
                <Row gutter={[16, 16]}>
                  {categories.map(category => (
                    <Col xs={24} sm={12} lg={8} xl={6} key={category.id}>
                      <CourseCategoryCard
                        category={category}
                        courseCount={courseStats.byCategory[category.id] || 0}
                        onEdit={() => handleEditCategory(category)}
                        onDelete={() => handleDeleteCategory(category)}
                      />
                    </Col>
                  ))}
                </Row>
              </Card>
            </TabPane>

            <TabPane 
              tab={
                <span>
                  <FilterOutlined />
                  课程统计
                </span>
              } 
              key="statistics"
            >
              <Card className={styles.statisticsCard}>
                <Row gutter={[16, 16]}>
                  {courses.map(course => {
                    const courseCategories = getCourseCategories(course);
                    return (
                      <Col xs={24} sm={12} lg={8} xl={6} key={course.id}>
                        <CourseCard
                          course={course}
                          categories={courseCategories}
                          onEdit={() => handleEditCourse(course)}
                          onDelete={() => handleDeleteCourse(course)}
                        />
                      </Col>
                    );
                  })}
                </Row>
              </Card>
            </TabPane>
          </Tabs>
        </Spin>
      </div>

      {/* 课程表单模态框 */}
      <Modal
        title={courseFormMode === 'create' ? '添加课程' : '编辑课程'}
        open={showCourseForm}
        onCancel={() => {
          setShowCourseForm(false);
          setCurrentCourse(null);
          setSearchParams({});
        }}
        footer={null}
        width={700}
        destroyOnHidden
      >
        <CourseForm
          visible={showCourseForm}
          course={currentCourse || undefined}
          categories={categories}
          mode={courseFormMode}
          onSubmit={handleCourseFormSubmit}
          onCancel={() => {
            setShowCourseForm(false);
            setCurrentCourse(null);
            setSearchParams({});
          }}
        />
      </Modal>

      {/* 分类表单模态框 */}
      <Modal
        title={categoryFormMode === 'create' ? '添加分类' : '编辑分类'}
        open={showCategoryForm}
        onCancel={() => {
          setShowCategoryForm(false);
          setCurrentCategory(null);
          setSearchParams({});
        }}
        footer={null}
        width={500}
        destroyOnHidden
      >
        <CourseCategoryForm
          visible={showCategoryForm}
          category={currentCategory || undefined}
          mode={categoryFormMode}
          onSubmit={handleCategoryFormSubmit}
          onCancel={() => {
            setShowCategoryForm(false);
            setCurrentCategory(null);
            setSearchParams({});
          }}
        />
      </Modal>
    </div>
  );
});

CoursePage.displayName = 'CoursePage';

export default CoursePage;